const app = getApp()
Page({
  data: {
    searching: false,
    isAvailable: false,
    isToasting: false,
    devicesList: [],
    connectedDevice: []
  },
  Search: function () {
    var that = this
    if (!that.data.searching) {
      wx.closeBluetoothAdapter({
        complete: function (res) {
          console.log(res)
          wx.openBluetoothAdapter({
            success: function (res) {
              console.log(res)
              wx.getBluetoothAdapterState({
                success: function (res) {
                  console.log(res)
                  if (!res.discovering && res.available) {
                    wx.startBluetoothDevicesDiscovery({
                      allowDuplicatesKey: false,
                      success: function (res) {
                        app.globalData.BLE.devicesList = []
                        app.globalData.BLE.connectedDevice = []
                        console.log(res)
                        that.setData({
                          searching: true,
                          devicesList: [],
                          connectedDevice: []
                        })
                      }
                    })
                  }
                }
              })
            },
            fail: function (res) {
              console.log(res)
              wx.showModal({
                title: '提示',
                content: '请检查手机蓝牙是否打开',
                showCancel: false,
                success: function (res) {
                  that.setData({
                    searching: false
                  })
                }
              })
            }
          })
        }
      })
    }
    else {
      wx.stopBluetoothDevicesDiscovery({
        success: function (res) {
          console.log(res)
          that.setData({
            searching: false
          })
        }
      })
    }
  },
  Connect: function (e) {
    var that = this
    var advertisData, name
    console.log(e.currentTarget.id)
    for (var i = 0; i < that.data.devicesList.length; i++) {
      if (e.currentTarget.id == that.data.devicesList[i].deviceId) {
        name = that.data.devicesList[i].name
        advertisData = that.data.devicesList[i].advertisData
      }
    }
    wx.stopBluetoothDevicesDiscovery({
      success: function (res) {
        console.log(res)
        that.setData({
          searching: false
        })
      }
    })
    wx.showLoading({
      title: '连接蓝牙设备中...',
    })
    /**关闭已连接的蓝牙设备 */
    if (that.data.connectedDevice.length > 0) {
      console.log(that.data.connectedDevice[0].name)
      wx.closeBLEConnection({
        deviceId: that.data.connectedDevice[0].deviceId,
        complete: function (res) {
          console.log(res);
        }
      })
    }

    wx.createBLEConnection({
      deviceId: e.currentTarget.id,
      timeout: 5000,
      success: function (res) {
        console.log(res)
        wx.hideLoading()
        wx.showToast({
          title: '连接成功',
          icon: 'success',
          duration: 1000
        })
        /* 清空已连接设备列表 */
        app.globalData.BLE.connectedDevice = []
        app.globalData.BLE.connected = true
        that.setData({
          connectedDevice: []
        })
        app.globalData.BLE.connectedDeviceId = e.currentTarget.id
        that.GetConnectedDevices()
        app.NotifyBLE()
        /*
        wx.navigateTo({
          url: '../device/device?connectedDeviceId=' + e.currentTarget.id + '&name=' + name
        })*/
      },
      fail: function (res) {
        console.log(res)
        wx.hideLoading()
        wx.showModal({
          title: '提示',
          content: '连接失败',
          showCancel: false
        })
      }
    })
  },
  onLoad: function (options) {
    /*
    console.log(111)
    this.initBle()*/
    
    var that = this
    var list_height = ((app.globalData.SystemInfo.windowHeight - 50) * (750 / app.globalData.SystemInfo.windowWidth)) - 60
    that.setData({
      list_height: list_height
    })

    /*
    setInterval(function () {

      //循环执行代码 
      if (!that.data.isAvailable && !that.data.isToasting) {
        that.initBle()
        //已经弹窗
        that.setData({
          isToasting: true
        })

        wx.showModal({
          title: '提示',
          content: '请打开蓝牙和GPS！',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {

              //没有弹窗
              that.setData({
                isToasting: false
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
    }, 5000) //循环时间 这里是5秒
    */
    wx.onBluetoothAdapterStateChange(function (res) {
      console.log(res)
      that.setData({
        searching: res.discovering
      })
      if (res.available) {

      } else if (!res.available) {
        that.setData({
          searching: false,
          isAvailable: false
        })
      }
    })
    wx.onBluetoothDeviceFound(function (devices) {
      //剔除重复设备，兼容不同设备API的不同返回值
      var isnotexist = true
      if (devices.deviceId && devices.name != '') {
        if (devices.advertisData)
        {
          devices.advertisData = app.buf2hex(devices.advertisData)
        }
        else
        {
          devices.advertisData = ''
        }
        console.log(devices)
        for (var i = 0; i < that.data.devicesList.length; i++) {
          if (devices.deviceId == that.data.devicesList[i].deviceId) {
            isnotexist = false
          }
        }
        if (isnotexist) {
          that.data.devicesList.push(devices)
        }
      }
      else if (devices.devices && devices.devices[0].name != '') {
        if (devices.devices[0].advertisData)
        {
          devices.devices[0].advertisData = app.buf2hex(devices.devices[0].advertisData)
        }
        else
        {
          devices.devices[0].advertisData = ''
        }
        console.log(devices.devices[0])
        for (var i = 0; i < that.data.devicesList.length; i++) {
          if (devices.devices[0].deviceId == that.data.devicesList[i].deviceId) {
            isnotexist = false
          }
        }
        if (isnotexist) {
          that.data.devicesList.push(devices.devices[0])
        }
      }
      else if (devices[0] && devices[0].name != '') {
        if (devices[0].advertisData)
        {
          devices[0].advertisData = app.buf2hex(devices[0].advertisData)
        }
        else
        {
          devices[0].advertisData = ''
        }
        console.log(devices[0])
        for (var i = 0; i < devices_list.length; i++) {
          if (devices[0].deviceId == that.data.devicesList[i].deviceId) {
            isnotexist = false
          }
        }
        if (isnotexist) {
          that.data.devicesList.push(devices[0])
        }
      }
      app.globalData.BLE.devicesList = that.data.devicesList
      that.setData({
        devicesList: that.data.devicesList
      })
    })
  },
  onReady: function () {

  },
  onShow: function () {
    var that = this
    that.setData({
      devicesList: app.globalData.BLE.devicesList,
      connectedDevice: app.globalData.BLE.connectedDevice
    })
  },
  onHide: function () {
    var that = this
    /*
    that.setData({
      devicesList: []
    })*/
    if (that.data.searching) {
      wx.stopBluetoothDevicesDiscovery({
        success: function (res) {
          console.log(res)
          that.setData({
            searching: false
          })
        }
      })
    }
  },
  //初始化蓝牙
  initBle: function () {
    wx.closeBluetoothAdapter({
      complete: function (res) {
        console.log(res)
      }
    })
    var that = this;
    //打开蓝牙适配器
    wx.openBluetoothAdapter({
      success: function (res) {

        //使能按钮
        console.log(res)
        that.setData({
          isAvailable: true
        })
      },
      fail: function (res) {
        // fail
        console.log(res)
        that.setData({
          searching: false
        })
      },
      complete: function (res) {
        // complete
      }
    })
  },
  /**
   * @description: 
   * @param {type} 
   * @return: 
   */
  GetConnectedDevices: function () {
    var that = this;
    wx.getConnectedBluetoothDevices({
      success(res) {
        console.log(res)
        app.globalData.BLE.connectedDevice = res.devices
        that.setData({
          connectedDevice: res.devices
        })
        console.log(that.data.connectedDevice)
        if (that.data.connectedDevice.length > 0) {
          for (let i = 0; i < that.data.devicesList.length; i++) {
            if (that.data.devicesList[i].name == that.data.connectedDevice[0].name) {
              that.data.devicesList.splice(i, 1)
              that.setData({
                devicesList: that.data.devicesList
              })
              app.globalData.BLE.devicesList = that.data.devicesList
              break
            }
          }
        }
      },
      fail(res) {
        console.log(res)
      }
    })
  }
})
